/**
 * @description: axios封装
 * @date: 2022-04-18 17:08
 */
import axios from 'axios'
import router from '../router'
import { useUserStore } from '../store/user'
import { useMainStore } from '../store/main'
import { defaultRequestErrMsg } from '../config/global'
import cookie from 'js-cookie'
import { authorization } from '../config/cacheKey'

// NOTE 在非组件中，要在使用前注册store
// getActivePinia was called with no active Pinia. Did you forget to install pinia?
var userStore, mainStore
var ajaxNum = 0

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  withCredentials: false,
  timeout: 10000
})

// axios请求拦截器
service.interceptors.request.use(
  config => {
    ajaxNum++
    if (!userStore) {
      userStore = useUserStore()
    }
    if (!mainStore) {
      mainStore = useMainStore()
    }
    // 已登录，将token带在请求头
    if (userStore.token) {
      config.headers.authorization = userStore.token
    }
    // 如果携带isLoading参数，添加加载动效
    if (config.isLoading) {
      mainStore.setLoading(true)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// axios响应拦截器
service.interceptors.response.use(
  response => {
    ajaxNum--
    if (ajaxNum === 0) {
      mainStore.setLoading(false)
    }
    const res = response.data
    if (res.status === 3906) { // 3906,没有token
      window.$message && window.$message.error('请先登录')
      router.replace('/login')
      return Promise.reject(res)
    }
    if (res.status === 40004) { // 40004,token失效
      window.$message && window.$message.error('登录状态失效，请重新登录')
      cookie.remove(authorization)
      userStore.setToken(undefined)
      router.replace('/login')
      return Promise.reject(res)
    }
    if (res.status === 200) {
      return Promise.resolve(res)
    } else if (res.message) {
      return Promise.reject(res)
    } else {
      return Promise.reject({ ...res, message: defaultRequestErrMsg })
    }
  },
  error => {
    ajaxNum--
    if (ajaxNum === 0) {
      mainStore.setLoading(false)
    }
    let message = ''
    if (error.message && error.message.indexOf('timeout') > -1) {
      message = '请求超时，请稍后重试！'
    } else {
      message = '请求失败，请稍后重试！'
    }
    return Promise.reject({ message })
  }
)

export default service
